import grpc
from concurrent import futures
import inventory_pb2
import inventory_pb2_grpc

class InventoryService(inventory_pb2_grpc.InventoryServiceServicer):
    def __init__(self):
        self.stocks = {"product_001": 100}  # 模拟库存数据

    def DeductStock(self, request, context):
        product_id = request.product_id
        quantity = request.quantity
        if self.stocks.get(product_id, 0) >= quantity:
            self.stocks[product_id] -= quantity
            return inventory_pb2.DeductResponse(success=True, message="扣减成功")
        else:
            return inventory_pb2.DeductResponse(success=False, message="库存不足")

def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    inventory_pb2_grpc.add_InventoryServiceServicer_to_server(InventoryService(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    server.wait_for_termination()

if __name__ == '__main__':
    serve()